<template>
  <div class="app-main-container">
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      @handleQuery="getList(1)"
      @changeForm="getList(1)"
      @clear="clear"
    />
    <div v-if="meta.indexOf('VenueAdd') > -1" class="doumee_table_header">
      <el-button
        v-if="meta.indexOf('VenueAdd') > -1"
        v-preventReClick
        type="primary"
        @click="toEdit()"
      >{{ translate("add") }}</el-button>
    </div>
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-table"
    >
      <el-table-column
        align="center"
        :label="translate('shbm')"
        show-overflow-tooltip
        min-width="100"
      >
        <span>{{ shopId }}</span>
      </el-table-column>
      <el-table-column
        align="center"
        :label="translate('venueId')"
        prop="id"
        show-overflow-tooltip
        min-width="140"
        sortable
      />
      <el-table-column
        align="center"
        :label="translate('venueName')"
        show-overflow-tooltip
        prop="name"
        min-width="200"
      />
      <el-table-column
        align="center"
        :label="translate('venueAddr')"
        prop="detailedAddress"
        show-overflow-tooltip
        min-width="280"
      />
      <el-table-column
        align="center"
        :label="translate('businessHours')"
        min-width="140"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ scope.row.openTimeStart }} - {{ scope.row.openTimeEnd }}
        </template>
      </el-table-column>
      <el-table-column
        :label="translate('sort')"
        min-width="100"
        align="center"
        sortable
        prop="sort"
        show-overflow-tooltip
        sort-by="sort"
        :sort-orders="['descending']"
      />
      <el-table-column
        align="center"
        :label="translate('businessStatus')"
        min-width="120"
        fixed="right"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.openStatus"
            :active-value="'1'"
            :inactive-value="'0'"
            :disabled="meta.indexOf('VenueStatusEdit') == -1"
            @change="stateChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column width="1" />
      <el-table-column
        :label="translate('handle')"
        min-width="200"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <div class="flex-cc">
            <el-button
              v-if="meta.indexOf('VenueEdit') > -1"
              v-preventReClick
              type="text"
              @click="toEdit(scope.row.id)"
            >{{ translate("edit") }}</el-button>
            <el-button
              v-if="meta.indexOf('VenueAlbumStatusEdit') > -1"
              v-preventReClick
              type="text"
              @click="VenueOpenService(scope.row)"
            >{{
              scope.row.albumStatus == 1 ? translate('closeService') : translate('openService')
            }}</el-button>
            <!-- v-if="meta.indexOf('VenueOpenService') > -1" -->
            <el-button
              v-preventReClick
              type="text"
              @click="toVenue(scope.row)"
            >{{ translate('enterVenue') }}</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      :total="total"
      :page="pagination.page"
      @current-change="getList"
      @SizeChange="handleSizeChange"
    />
    <el-dialog
      :close-on-click-modal="modalDialog"
      :lose-on-press-escape="modalDialog"
      :title="translate('ydzp')"
      :visible.sync="dialogVisible"
      width="30%"
      :center="true"
    >
      <el-form
        ref="ruleForm"
        :model="service"
        :rules="rules"
        label-width="auto"
      >
        <el-form-item :label="translate('openService')" prop="albumStatus">
          <el-radio-group v-model="service.albumStatus">
            <el-radio label="1">{{ translate("kaitong") }}</el-radio>
            <el-radio label="0">{{ translate("close") }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">{{
          translate("cancel")
        }}</el-button>
        <el-button v-preventReClick type="primary" @click="confirmOpen">{{
          translate("enter")
        }}</el-button>
      </span>
    </el-dialog>
    <Edit
      v-if="isShowEdit"
      ref="EditRef"
      @close="isShowEdit = false"
      @success="getList"
    />
  </div>
</template>

<script>
import { venueUrl, venueGrayUrl, updateVenueStatus, venueList, updateVenueAlbumStatus } from '@/api'
import { getToken } from '@/utils/auth'
import { parseTime } from '@/utils/index'
import { queryFormConfig } from './config'
import Pagination from '@/components/paginations'
import Edit from './edit.vue'
function findIndex(str, cha, num) {
  var x = str.indexOf(cha)
  for (var i = 0; i < num; i++) {
    x = str.indexOf(cha, x + 1)
    if (x === -1) break
  }
  return x
}
export default {
  name: 'VenueList',
  components: {
    Pagination,
    Edit
  },
  data() {
    return {
      isShowEdit: false,

      modalDialog: this.$store.state.app.dialog,
      queryFormConfig,
      values: true,
      dialogVisible: false,
      list: [],
      listLoading: true,
      pagination: {
        page: 1,
        rows: 10
      },
      param: {},
      service: {},
      total: 0,
      meta: [],
      filters: {},
      shopId: localStorage.getItem('shopId'),
      openStatus: [
        { value: '1', label: this.translate('zcye') },
        { value: '0', label: this.translate('closeDown') }
      ],
      rules: {
        albumStatus: [
          { required: true, message: this.translate('kaitongPlace'), trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.getList(1)
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  activated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  methods: {
    handleSizeChange(value) {
      this.pagination.rows = value
      this.getList(1)
    },
    // 获取场馆列表
    getList(page) {
      // 获取会员列表
      this.listLoading = true
      const { filters, pagination } = this
      if (page) {
        pagination.page = page
        this.pagination.page = page
      }
      if (pagination.page === 1) {
        pagination.firstQueryTime = parseTime(new Date())
      }
      venueList({
        pagination,
        param: { ...filters }
      })
        .then((res) => {
          this.listLoading = false
          if (res.errorCode === '000000') {
            this.list = res.recordList
            this.total = res.totalCount
          }
        })
        .catch((err) => {
          console.log(err)
          this.listLoading = false
        })
    },
    // 编辑场馆
    toEdit(id) {
      this.isShowEdit = true
      this.$nextTick(() => {
        this.$refs.EditRef.isShowModal = true
        if (id) {
          this.$refs.EditRef.id = id
          this.$refs.EditRef.mainName = this.translate('venueEdit')
          this.$refs.EditRef.getVenueInfo(id)
        } else {
          this.$refs.EditRef.venueInfo = {
            selectCofigList: [],
            facilitys: []
          }
          this.$refs.EditRef.getVenueServiceList()
        }
      })
    },
    // 开通服务
    VenueOpenService(row) {
      let param = JSON.stringify(row)
      param = JSON.parse(param)
      this.service = param
      this.dialogVisible = true
    },
    confirmOpen() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const param = { ...this.service }
          updateVenueAlbumStatus({
            param: {
              id: param.id,
              status: param.albumStatus,
              openStatus: param.openStatus
            }
          }).then(res => {
            if (res.errorCode === '000000') {
              this.dialogVisible = false
              this.$message.success(param.albumStatus === 1 || param.albumStatus === '1' ? this.translate('openScs') : this.translate('closeScs'))
              this.getList(1)
            }
          }).catch(er => {
            console.log(er)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    toVenueAdd() {
      this.$router.push({
        name: 'VenueEdit'
      })
    },
    toVenue(s) {
      const e = { ...s }
      e.describe = null
      e.detailedAddress = null
      e.editTime = null
      e.editor = null
      e.picture = null
      const shopId = localStorage.getItem('shopId')
      const userId = sessionStorage.getItem('userId')
      const token = getToken()

      const str = window.location.href
      const index = findIndex(str, '_', 0)
      const grayFlag = str.indexOf('gray')
      if (grayFlag > -1) {
        window.open(str.slice(0, index + 1) + venueGrayUrl + '?venueId=' + e.id + '&shopId=' + shopId + '&userId=' + userId + '&name=' + e.name + '&token=' + token + '&venueInfo=' + JSON.stringify(e), '_blank')
      } else {
        window.open(str.slice(0, index + 1) + venueUrl + '?venueId=' + e.id + '&shopId=' + shopId + '&userId=' + userId + '&name=' + e.name + '&token=' + token + '&venueInfo=' + JSON.stringify(e), '_blank')
      }
    },
    // 修改场馆营业状态
    // toConfigUpdate(e, id, openStatus) {
    //   updateVenueStatus({ param: { id, [openStatus]: e }}).then((res) => {
    //     if (res.errorCode !== '000000') return
    //     this.$message.success(this.translate('editScs'))
    //     this.getList(1)
    //   })
    // },
    stateChange(v) {
      const obj = { ...v }
      const arr = this.list
      const that = this
      this.listLoading = true
      updateVenueStatus({
        param: {
          id: obj.id,
          openStatus: obj.openStatus
        }
      })
        .then(res => {
          if (res.errorCode === '000000') {
            if (obj.openStatus === '0') {
              that.$message.success(this.translate('jyScs'))
            } else {
              that.$message.success(this.translate('qyScs'))
            }
            that.getList(1)
          } else {
            arr.forEach(e => {
              if (e.id === obj.id) {
                e.openStatus = obj.openStatus === '1' ? '0' : '1'
              }
            })
            that.list = arr
            that.listLoading = false
          }
        }).catch(() => {
          arr.forEach(e => {
            if (e.id === obj.id) {
              e.openStatus = obj.openStatus === '1' ? '0' : '1'
            }
          })
          that.list = arr
          that.listLoading = false
        })
    },
    // 清空
    clear() {
      this.filters = {}
      this.getList(1)
    }
  }
}
</script>
